package com.rdc.jiajiadictionary.data.gethistory;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.rdc.jiajiadictionary.bean.Word;
import com.rdc.jiajiadictionary.database.DataBaseHelper;

import java.util.ArrayList;
import java.util.List;

public class HistoryModel implements com.rdc.jiajiadictionary.data.gethistory.HistoryModelInterface {
    private Context context;
    public HistoryModel(Context context){
        this.context = context;
    }

    /**
     * 从数据库中获取到历史搜索记录
     * @return 返回从数据库中获取到的历史记录list
     */
    @Override
    public List<Word> getWordsFromDatabase() {
        List<Word> words = new ArrayList<Word>();
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context,"word.db",null,1);
        SQLiteDatabase db = dataBaseHelper.getReadableDatabase();
        Cursor cursor = db.query("history",null,null,null,null,null,"id desc");
        if (cursor.moveToFirst()){
            do {
                Word word = new Word();
                word.setWord_name(cursor.getString(cursor.getColumnIndexOrThrow("word_name")));
                word.setPart(cursor.getString(cursor.getColumnIndexOrThrow("word_parts")));
                words.add(word);
            }while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return words;
    }

    /**
     * 删除数据库中的历史记录
     */
    @Override
    public void deleteHistoryFromDatabase() {
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context,"word.db",null,1);
        SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
        db.delete("history",null,null);
        db.close();
    }

}
